package cn.edu.hnu.matching.exception;

import cn.dev33.satoken.exception.NotLoginException;
import cn.edu.hnu.matching.common.Result;
import cn.edu.hnu.matching.common.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理器
 *
 * @author n70huihui
 * @since 2025-04-10
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<Void> methodArgNotValidExceptionHandler(MethodArgumentNotValidException e) {
        log.error("MethodArgumentNotValidException", e);
        String errorMsg = e.getBindingResult().getAllErrors().get(0).getDefaultMessage();
        return Result.error(ResultCode.PARAMS_ERROR, errorMsg);
    }

    @ExceptionHandler(BusinessException.class)
    public Result<Void> businessExceptionHandler(BusinessException e) {
        log.error("BusinessException", e);
        return Result.customize(e.getCode(), e.getMessage());
    }

    @ExceptionHandler(RuntimeException.class)
    public Result<Void> runtimeExceptionHandler(RuntimeException e) {
        log.error("RuntimeException", e);
        return Result.error(ResultCode.SYSTEM_ERROR);
    }

    @ExceptionHandler(NotLoginException.class)
    public Result<Void> notLoginExceptionHandler(RuntimeException e) {
        log.error("NotLoginException", e);
        return Result.error(ResultCode.NOT_LOGIN_ERROR);
    }

}
